#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h> 
#include <stdlib.h> 
#include <string.h>
#include <unistd.h>

#define REVD_BUFFER_BYTES 4096

char *tcp_send(const char * request_str,uint32_t ip,uint16_t port) {
    int sock;
    uint32_t request_str_len=strlen(request_str);
    struct sockaddr_in server_addr;
    char revd_buffer[REVD_BUFFER_BYTES];

    if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
        return NULL;
    }
    server_addr.sin_family      = AF_INET;
    server_addr.sin_addr.s_addr = ip;
    server_addr.sin_port        = htons(port);
    if (connect(sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
        return NULL;
    }
    if (send(sock, request_str, request_str_len, 0) != request_str_len) {
        return NULL;
    }
    char *revd_bytes=NULL;
    int32_t current_revd=0;
    uint32_t total_revd=0;
    while (1) {
        if ((current_revd = recv(sock, revd_buffer, REVD_BUFFER_BYTES-1 , 0)) <= 0) {
            break;
        }
        total_revd += current_revd;
        if (revd_bytes) {
            revd_bytes=realloc(revd_bytes,total_revd);
        } else {
            revd_bytes=malloc(total_revd);
        }
        revd_buffer[current_revd]=0;
        strncat(revd_bytes,revd_buffer,current_revd);
    }
    close(sock);
    return revd_bytes;
}
